package edu.arizona.arid.akshen;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.sql.Timestamp;
import java.util.Date;

import org.json.JSONObject;

import edu.arizona.arid.akshen.entity.Message;
import edu.arizona.arid.akshen.entity.User;

/**
 * 
 * @author Sumin Byeon
 */
public final class ServerThread extends Thread {

	private ServerDelegate delegate;
	private Client client;

	public ServerThread(ServerDelegate delegate, Client client) {
		this.delegate = delegate;
		this.client = client;
	}

	@Override
	public void run() {
		InputStream in = null;
		try {
			in = client.getInputStream();
			Message message = new Message();
			message.setType(Message.Type.Text);

			byte[] buf = new byte[1024*4];
			while (true) {
				// TODO: temporary
				int read = in.read(buf);
				if(read < 0) {
					break;
				}
				String rawText = new String(buf, 0, read);
				
				JSONObject json = new JSONObject(rawText);
				
				message.setUser(new User(json.getString("user")));
				message.setText(json.getString("text"));
				message.setDate(new Timestamp(new Date().getTime()));
			
				delegate.messageReceived(client, message);
			}
		}
		catch (SocketException e) {
			System.out.println("Connection is gone!");
			delegate.exceptionRaised(e);
		}
		catch (EOFException e) {
			delegate.exceptionRaised(e);
		}
		catch (IOException e) {
			delegate.exceptionRaised(e);
		}
		catch (Exception e) {
			delegate.exceptionRaised(e);
		}
		finally {
			delegate.disconnected(client);
		}
	}
}
